<template>
  <div class="user-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="page-title">
        <el-icon class="title-icon"><User /></el-icon>
        <span>用户管理</span>
      </div>
      <div class="page-description">
        管理系统用户信息，包括用户的增删改查、状态管理等操作
      </div>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><Search /></el-icon>
            <span>搜索条件</span>
          </div>
        </div>
      </template>
      <el-form :model="searchForm" :inline="true" @submit.prevent="handleSearch">
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入用户名"
            clearable
            style="width: 200px"
            :prefix-icon="User"
          />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input
            v-model="searchForm.realName"
            placeholder="请输入真实姓名"
            clearable
            style="width: 200px"
            :prefix-icon="UserFilled"
          />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input
            v-model="searchForm.email"
            placeholder="请输入邮箱"
            clearable
            style="width: 200px"
            :prefix-icon="Message"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">
            搜索
          </el-button>
          <el-button @click="handleReset" :icon="Refresh">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="operation-card" shadow="never">
      <div class="operation-wrapper">
        <div class="left-operations">
          <!-- 新增用户按钮 -->
          <el-button 
            type="primary" 
            @click="handleAdd" 
            :icon="Plus"
          >
            新增用户
          </el-button>
          
          <!-- 批量启用按钮 -->
          <el-button 
            type="success" 
            @click="handleBatchEnable" 
            :icon="Check" 
            :disabled="!hasSelected"
          >
            批量启用
          </el-button>
          
          <!-- 批量禁用按钮 -->
          <el-button 
            type="warning" 
            @click="handleBatchDisable" 
            :icon="Close" 
            :disabled="!hasSelected"
          >
            批量禁用
          </el-button>
          
          <!-- 批量删除按钮 -->
          <el-button 
            type="danger" 
            @click="handleBatchDelete" 
            :icon="Delete" 
            :disabled="!hasSelected"
          >
            批量删除
          </el-button>
        </div>
        <div class="right-operations">
          <el-button @click="handleRefresh" :icon="Refresh" circle />
        </div>
      </div>
    </el-card>

    <!-- 用户表格 -->
    <el-card class="table-card" shadow="never">

      
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><List /></el-icon>
            <span>用户列表</span>
            <el-tag type="info" size="small">{{ pagination.total }} 条记录</el-tag>
          </div>
          <div class="header-right">
            <el-switch
              v-model="tableConfig.stripe"
              active-text="斑马纹"
              inactive-text="普通"
              size="small"
            />
            <el-switch
              v-model="tableConfig.border"
              active-text="边框"
              inactive-text="无边框"
              size="small"
            />
          </div>
        </div>
      </template>
      
      <el-table
        v-loading="loading"
        :data="userList"
        :border="tableConfig.border"
        :stripe="tableConfig.stripe"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        row-key="id"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="序号" width="80" />
        <el-table-column prop="avatar" label="头像" width="80" align="center">
          <template #default="{ row }">
            <el-avatar 
              :size="40" 
              :src="row.avatar" 
              :icon="User"
              class="user-avatar"
            />
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" min-width="120">
          <template #default="{ row }">
            <span class="username-text">{{ row.username }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="realName" label="真实姓名" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="200">
          <template #default="{ row }">
            <el-link :href="`mailto:${row.email}`" type="primary" :underline="false">
              {{ row.email }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" min-width="130">
          <template #default="{ row }">
            <el-link :href="`tel:${row.phone}`" type="primary" :underline="false">
              {{ row.phone }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" min-width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'" effect="dark">
              <el-icon v-if="row.status === 1"><Check /></el-icon>
              <el-icon v-else><Close /></el-icon>
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="roleNames" label="角色" min-width="200">
          <template #default="{ row }">
            <div class="role-tags">
              <el-tag
                v-for="roleName in row.roleNames"
                :key="roleName"
                type="info"
                size="small"
                effect="plain"
              >
                {{ roleName }}
              </el-tag>
              <el-tag v-if="!row.roleNames || row.roleNames.length === 0" type="warning" size="small" effect="plain">
                无角色
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="180" sortable>
          <template #default="{ row }">
            <div class="time-cell">
              <el-icon><Clock /></el-icon>
              <span>{{ formatDateTime(row.createTime) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <div class="operation-buttons">
              <!-- 分配角色按钮 -->
              <el-tooltip content="分配角色" placement="top">
                <el-button 
                  type="success" 
                  size="small" 
                  circle
                  @click="openAssignRoleDialog(row)" 
                  :icon="UserFilled"
                />
              </el-tooltip>
              
              <!-- 编辑用户按钮 -->
              <el-tooltip content="编辑用户" placement="top">
                <el-button 
                  type="primary" 
                  size="small" 
                  circle
                  @click="handleEdit(row)" 
                  :icon="Edit"
                />
              </el-tooltip>
              
              <!-- 启用/禁用用户按钮 -->
              <el-tooltip :content="row.status === 1 ? '禁用用户' : '启用用户'" placement="top">
                <el-button
                  :type="row.status === 1 ? 'warning' : 'success'"
                  size="small"
                  circle
                  @click="handleToggleStatus(row)"
                  :icon="row.status === 1 ? Close : Check"
                />
              </el-tooltip>
              
              <!-- 查看详情按钮 -->
              <el-tooltip content="查看详情" placement="top">
                <el-button 
                  type="info" 
                  size="small" 
                  circle
                  @click="handleView(row)" 
                  :icon="View"
                />
              </el-tooltip>
              
              <!-- 删除用户按钮 -->
              <el-tooltip content="删除用户" placement="top">
                <el-button 
                  type="danger" 
                  size="small" 
                  circle
                  @click="handleDelete(row)" 
                  :icon="Delete"
                />
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          :current-page="pagination.pageNum"
          :page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          :pager-count="7"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userFormRules"
        label-width="100px"
        class="user-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input 
                v-model="userForm.username" 
                placeholder="请输入用户名"
                :prefix-icon="User"
                :disabled="!!userForm.id"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="realName">
              <el-input 
                v-model="userForm.realName" 
                placeholder="请输入真实姓名"
                :prefix-icon="UserFilled"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="密码" prop="password" v-if="!userForm.id">
              <el-input
                v-model="userForm.password"
                type="password"
                placeholder="请输入密码"
                show-password
                :prefix-icon="Lock"
              />
            </el-form-item>
            <el-form-item label="邮箱" prop="email" v-else>
              <el-input 
                v-model="userForm.email" 
                placeholder="请输入邮箱"
                :prefix-icon="Message"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input 
                v-model="userForm.phone" 
                placeholder="请输入手机号"
                :prefix-icon="Phone"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email" v-if="!userForm.id">
              <el-input 
                v-model="userForm.email" 
                placeholder="请输入邮箱"
                :prefix-icon="Message"
              />
            </el-form-item>
            <el-form-item label="状态" prop="status" v-else>
              <el-radio-group v-model="userForm.status">
                <el-radio :label="1">
                  <el-icon><Check /></el-icon>
                  启用
                </el-radio>
                <el-radio :label="0">
                  <el-icon><Close /></el-icon>
                  禁用
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status" v-if="!userForm.id">
              <el-radio-group v-model="userForm.status">
                <el-radio :label="1">
                  <el-icon><Check /></el-icon>
                  启用
                </el-radio>
                <el-radio :label="0">
                  <el-icon><Close /></el-icon>
                  禁用
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="头像" prop="avatar" v-else>
              <div class="avatar-display">
                <el-avatar :size="60" :src="userForm.avatar" :icon="User" />
                <div class="avatar-info">
                  <p class="avatar-text">头像仅可在个人信息中修改</p>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="userForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      v-model="assignDialogVisible"
      :title="`分配角色：${assignUser?.username || ''}`"
      width="520px"
      :close-on-click-modal="false"
    >
      <el-checkbox-group v-model="checkedRoleIds" class="role-checkbox-group">
        <el-checkbox 
          v-for="role in allRoles" 
          :key="role.id" 
          :label="role.id"
        >{{ role.roleName }}（{{ role.roleCode }}）</el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <el-button @click="assignDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAssignRoles" :loading="assignLoading">保存</el-button>
      </template>
    </el-dialog>

    <!-- 用户详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="用户详情"
      width="600px"
      :close-on-click-modal="false"
    >
      <div v-if="currentUser" class="user-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户ID">{{ currentUser.id }}</el-descriptions-item>
          <el-descriptions-item label="用户名">{{ currentUser.username }}</el-descriptions-item>
          <el-descriptions-item label="真实姓名">{{ currentUser.realName }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ currentUser.email }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ currentUser.phone }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentUser.status === 1 ? 'success' : 'danger'">
              {{ currentUser.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="角色" :span="2">
            <el-tag
              v-for="roleName in currentUser.roleNames"
              :key="roleName"
              type="info"
              size="small"
              style="margin-right: 5px"
            >
              {{ roleName }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">
            {{ formatDateTime(currentUser.createTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间" :span="2">
            {{ formatDateTime(currentUser.updateTime) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  User, UserFilled, Search, Refresh, Plus, Check, Close, Delete, 
  List, Edit, View, Clock, Message, Phone, Lock 
} from '@element-plus/icons-vue'
import { userApi } from '@/api/user'
import { roleApi } from '@/api/role'
import { useAuthStore } from '@/stores/auth'

// 获取权限存储
const authStore = useAuthStore()

// 权限检查方法
const hasPermission = (permission) => {
  return authStore.hasPermission(permission)
}

// 检查是否有任何权限
const hasAnyPermission = (permissions) => {
  return authStore.hasAnyPermission(permissions)
}

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const dialogTitle = ref('')
const submitLoading = ref(false)
const userFormRef = ref()
const selectedUsers = ref([])
const currentUser = ref(null)

// 分配角色相关
const assignDialogVisible = ref(false)
const assignLoading = ref(false)
const assignUser = ref(null)
const allRoles = ref([])
const checkedRoleIds = ref([])

// 表格配置
const tableConfig = reactive({
  stripe: true,
  border: true
})

// 搜索表单
const searchForm = reactive({
  username: '',
  realName: '',
  email: '',
  status: null
})

// 用户表单
const userForm = reactive({
  id: null,
  username: '',
  password: '',
  realName: '',
  email: '',
  phone: '',
  status: 1,
  avatar: '',
  remark: ''
})

// 表单验证规则
const userFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '真实姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 分页信息
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 用户列表
const userList = ref([])

// 计算属性
const hasSelected = computed(() => selectedUsers.value.length > 0)

// 生命周期
onMounted(() => {
  fetchUserList()
})

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      orderBy: 'id',
      orderType: 'asc',
      ...searchForm
    }
    
    console.log('发送的排序参数:', params)
    
    const response = await userApi.getUserList(params)
    if (response.data.code === 200) {
      userList.value = response.data.data.list
      pagination.total = response.data.data.total
      console.log('接收到的用户列表:', userList.value)
    } else {
      ElMessage.error(response.data.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.pageNum = 1
  fetchUserList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    username: '',
    realName: '',
    email: '',
    status: null
  })
  pagination.pageNum = 1
  fetchUserList()
}

// 刷新
const handleRefresh = () => {
  fetchUserList()
  ElMessage.success('刷新成功')
}

// 新增用户
const handleAdd = () => {
  // 检查新增权限
  if (!authStore.hasPermission('system:user:add')) {
    ElMessage.warning('您没有新增用户的权限')
    return
  }
  
  dialogTitle.value = '新增用户'
  resetUserForm()
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  // 检查编辑权限
  if (!authStore.hasPermission('system:user:edit')) {
    ElMessage.warning('您没有编辑用户的权限')
    return
  }
  
  dialogTitle.value = '编辑用户'
  Object.assign(userForm, {
    id: row.id,
    username: row.username,
    password: '',
    realName: row.realName,
    email: row.email,
    phone: row.phone,
    status: row.status,
    avatar: row.avatar || '', // 保持原头像，不允许修改
    remark: row.remark || ''
  })
  dialogVisible.value = true
}

// 查看用户详情
const handleView = (row) => {
  // 检查查询权限
  if (!authStore.hasPermission('system:user:query')) {
    ElMessage.warning('您没有查看用户详情的权限')
    return
  }
  
  currentUser.value = row
  detailDialogVisible.value = true
}

// 删除用户
const handleDelete = async (row) => {
  // 检查删除权限
  if (!authStore.hasPermission('system:user:delete')) {
    ElMessage.warning('您没有删除用户的权限')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${row.username}" 吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }
    )
    
    const response = await userApi.deleteUser(row.id)
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      fetchUserList()
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 切换用户状态
const handleToggleStatus = async (row) => {
  // 检查编辑权限
  if (!authStore.hasPermission('system:user:edit')) {
    ElMessage.warning('您没有修改用户状态的权限')
    return
  }
  
  const newStatus = row.status === 1 ? 0 : 1
  const statusText = newStatus === 1 ? '启用' : '禁用'
  
  try {
    await ElMessageBox.confirm(
      `确定要${statusText}用户 "${row.username}" 吗？`,
      `确认${statusText}`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await userApi.updateUserStatus(row.id, newStatus)
    if (response.data.code === 200) {
      ElMessage.success(`${statusText}成功`)
      fetchUserList()
    } else {
      ElMessage.error(response.data.message || `${statusText}失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error(`${statusText}用户失败:`, error)
      ElMessage.error(`${statusText}失败`)
    }
  }
}

// 批量操作
const handleBatchEnable = async () => {
  // 检查编辑权限
  if (!authStore.hasPermission('system:user:edit')) {
    ElMessage.warning('您没有批量启用用户的权限')
    return
  }
  await handleBatchStatus(1, '启用')
}

const handleBatchDisable = async () => {
  // 检查编辑权限
  if (!authStore.hasPermission('system:user:edit')) {
    ElMessage.warning('您没有批量禁用用户的权限')
    return
  }
  await handleBatchStatus(0, '禁用')
}

const handleBatchStatus = async (status, statusText) => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请先选择要操作的用户')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要${statusText}选中的 ${selectedUsers.value.length} 个用户吗？`,
      `批量${statusText}`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const promises = selectedUsers.value.map(user => 
      userApi.updateUserStatus(user.id, status)
    )
    
    await Promise.all(promises)
    ElMessage.success(`批量${statusText}成功`)
    fetchUserList()
    selectedUsers.value = []
  } catch (error) {
    if (error !== 'cancel') {
      console.error(`批量${statusText}失败:`, error)
      ElMessage.error(`批量${statusText}失败`)
    }
  }
}

const handleBatchDelete = async () => {
  // 检查删除权限
  if (!authStore.hasPermission('system:user:delete')) {
    ElMessage.warning('您没有批量删除用户的权限')
    return
  }
  
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请先选择要删除的用户')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？此操作不可恢复！`,
      '批量删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }
    )

    const promises = selectedUsers.value.map(user => 
      userApi.deleteUser(user.id)
    )
    
    await Promise.all(promises)
    ElMessage.success('批量删除成功')
    fetchUserList()
    selectedUsers.value = []
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
}

// 提交表单
const handleSubmit = async () => {
  try {
    await userFormRef.value.validate()
    submitLoading.value = true
    
    // 编辑时不提交头像字段
    const submitData = { ...userForm }
    if (userForm.id) {
      delete submitData.avatar // 编辑时删除头像字段
    }
    
    const api = userForm.id ? userApi.updateUser : userApi.addUser
    const response = await api(submitData)
    
    if (response.data.code === 200) {
      ElMessage.success(userForm.id ? '更新成功' : '新增成功')
      dialogVisible.value = false
      fetchUserList()
    } else {
      ElMessage.error(response.data.message || (userForm.id ? '更新失败' : '新增失败'))
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

// 重置用户表单
const resetUserForm = () => {
  Object.assign(userForm, {
    id: null,
    username: '',
    password: '',
    realName: '',
    email: '',
    phone: '',
    status: 1,
    avatar: '',
    remark: ''
  })
  nextTick(() => {
    userFormRef.value?.clearValidate()
  })
}

// 关闭对话框
const handleDialogClose = () => {
  resetUserForm()
}

// 头像上传
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.pageNum = 1
  fetchUserList()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.pageNum = page
  fetchUserList()
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 加载所有角色（用于勾选）
const loadAllRoles = async () => {
  const res = await roleApi.getRoleList({ pageNum: 1, pageSize: 9999, orderBy: 'id', orderType: 'asc' })
  if (res.data.code === 200) {
    allRoles.value = res.data.data.list || []
  }
}

// 打开分配角色对话框
const openAssignRoleDialog = async (row) => {
  // 检查角色管理权限
  if (!authStore.hasPermission('system:role:edit')) {
    ElMessage.warning('您没有分配角色的权限')
    return
  }
  
  assignUser.value = row
  assignDialogVisible.value = true
  await loadAllRoles()
  const resp = await userApi.getUserRoleIds(row.id)
  if (resp.data.code === 200) {
    checkedRoleIds.value = resp.data.data || []
  }
}

// 提交分配角色
const submitAssignRoles = async () => {
  try {
    assignLoading.value = true
    const res = await userApi.assignRoles(assignUser.value.id, checkedRoleIds.value)
    if (res.data.code === 200) {
      ElMessage.success('分配角色成功')
      assignDialogVisible.value = false
      fetchUserList()
    } else {
      ElMessage.error(res.data.message || '分配角色失败')
    }
  } catch (e) {
    console.error('分配角色失败', e)
    ElMessage.error('分配角色失败')
  } finally {
    assignLoading.value = false
  }
}
</script>

<style scoped>
.user-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;
}

.page-title {
  display: flex;
  align-items: center;
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.title-icon {
  margin-right: 10px;
  font-size: 28px;
}

.page-description {
  font-size: 14px;
  opacity: 0.9;
}

.search-card,
.operation-card,
.table-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 6px;
}

.header-icon {
  font-size: 16px;
  color: var(--el-color-primary);
  margin-right: 2px;
}

.card-header .header-left span {
  font-weight: 500;
  color: #303133;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.operation-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-operations {
  display: flex;
  gap: 10px;
}

.right-operations {
  display: flex;
  gap: 10px;
}

.username-text {
  font-weight: 500;
  color: #303133;
}

.user-avatar {
  border: 2px solid #e4e7ed;
  transition: all 0.3s ease;
}

.user-avatar:hover {
  border-color: var(--el-color-primary);
  transform: scale(1.05);
}

.role-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.time-cell {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #666;
}

.operation-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
}

.operation-buttons .el-button {
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.operation-buttons .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.operation-buttons .el-button--primary {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  border: none;
}

.operation-buttons .el-button--primary:hover {
  background: linear-gradient(135deg, #337ecc 0%, #2d5aa0 100%);
}

.operation-buttons .el-button--success {
  background: linear-gradient(135deg, #67c23a 0%, #5daf34 100%);
  border: none;
}

.operation-buttons .el-button--success:hover {
  background: linear-gradient(135deg, #5daf34 0%, #529b2e 100%);
}

.operation-buttons .el-button--warning {
  background: linear-gradient(135deg, #e6a23c 0%, #cf9236 100%);
  border: none;
}

.operation-buttons .el-button--warning:hover {
  background: linear-gradient(135deg, #cf9236 0%, #b88230 100%);
}

.operation-buttons .el-button--info {
  background: linear-gradient(135deg, #909399 0%, #82848a 100%);
  border: none;
}

.operation-buttons .el-button--info:hover {
  background: linear-gradient(135deg, #82848a 0%, #73767a 100%);
}

.operation-buttons .el-button--danger {
  background: linear-gradient(135deg, #f56c6c 0%, #dc4e4e 100%);
  border: none;
}

.operation-buttons .el-button--danger:hover {
  background: linear-gradient(135deg, #dc4e4e 0%, #c23e3e 100%);
}

/* 操作列样式优化 */
:deep(.el-table .el-table__cell:last-child) {
  padding: 8px 12px;
}

:deep(.el-table .el-table__cell:last-child .cell) {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 工具提示样式优化 */
:deep(.el-tooltip__popper) {
  font-size: 12px;
  padding: 6px 10px;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px 0;
}

:deep(.el-pagination) {
  --el-pagination-font-size: 14px;
  --el-pagination-button-margin: 0 4px;
  --el-pagination-button-padding: 0 8px;
}

:deep(.el-pagination .el-pagination__total) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-pagination .el-pagination__sizes) {
  margin: 0 16px;
}

:deep(.el-pagination .el-pager li) {
  border-radius: 4px;
  margin: 0 2px;
}

:deep(.el-pagination .el-pager li.is-active) {
  background-color: var(--el-color-primary);
  color: white;
  font-weight: 600;
}

:deep(.el-pagination .btn-prev),
:deep(.el-pagination .btn-next) {
  border-radius: 4px;
  margin: 0 4px;
}

:deep(.el-pagination .el-pagination__jump) {
  margin-left: 16px;
}

.user-form {
  padding: 20px 0;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  text-align: center;
  line-height: 80px;
}

.avatar {
  width: 80px;
  height: 80px;
  display: block;
  object-fit: cover;
}

.avatar-display {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.avatar-info {
  flex: 1;
}

.avatar-text {
  margin: 0;
  font-size: 12px;
  color: #6c757d;
  line-height: 1.4;
}

.user-detail {
  padding: 20px 0;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 20px;
  margin-bottom: 10px;
}

:deep(.el-table) {
  width: 100% !important;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa;
}

:deep(.el-table .el-table__header-wrapper) {
  background-color: #fafafa;
}

:deep(.el-table .el-table__header th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-table .el-table__body td) {
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-table .el-table__body tr:hover > td) {
  background-color: #f5f7fa;
}

:deep(.el-tag) {
  border-radius: 4px;
}

:deep(.el-button) {
  border-radius: 4px;
}

:deep(.el-input__wrapper) {
  border-radius: 4px;
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 4px;
}

/* 复用原有样式，补充分配角色弹窗的样式 */
.role-checkbox-group {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px 16px;
  padding: 10px 5px;
  max-height: 360px;
  overflow: auto;
  border: 1px solid #eee;
  border-radius: 6px;
}

/* 其余样式保持不变 */
/* 响应式设计 */
@media (max-width: 768px) {
  .user-management {
    padding: 10px;
  }
  
  .operation-wrapper {
    flex-direction: column;
    gap: 15px;
  }
  
  .left-operations,
  .right-operations {
    width: 100%;
    justify-content: center;
  }
  
  .card-header {
    flex-direction: column;
    gap: 10px;
  }
}
</style> 